import 'package:flutter_admin/api/odoo/stock_materialcheck_odoo_api.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_materialcheckitem_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/stock_materialcheckitem.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheckitem/stock_materialcheckitem_dialog.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheckitem/stock_materialcheckitem_edit.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:intl/intl.dart';

class StockMaterialcheckitemInventory extends StatefulWidget {
  StockMaterialcheckitemInventory({Key? key, required this.stockMaterialcheckitem})
      : super(key: key);

  final StockMaterialcheckitem stockMaterialcheckitem;
  @override
  _StockMaterialcheckitemInventoryState createState() =>
      _StockMaterialcheckitemInventoryState();
}

class _StockMaterialcheckitemInventoryState
    extends State<StockMaterialcheckitemInventory> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'is_check', asc: false)]);
  StockMaterialcheckitem stockMaterialcheckitem = StockMaterialcheckitem();
  List<StockMaterialcheckitem> selectedList = [];
  var _subscription;
  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "stockMaterialcheckitemInventory")
        .listen(_onEnvent);
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) async{
    try {
      var scan = obj["scan"].toString();
      List scanList = scan.split("|");
      ResponseBodyApi res = await StockMaterialcheckitemOdooApi.toItemInfo(
          productorderno: scanList[0],
          productCode: scanList[1],
          locationCode: scanList[2],
      );
      if (res.success!){
        print(res.data);
        if(res.data.length == 1){
          StockMaterialcheckitem stockMaterialcheckitem = StockMaterialcheckitem.fromItemInfoMap(res.data[0]);
          _edit(stockMaterialcheckitem);
        }else{
          CryUtils.message("数剧错误。请联系管理员");
        }
      }
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  @override
  Widget build(BuildContext context) {

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        //isDisplayDesktop(context)?DataColumn(
        //  label: Text(S.of(context).operating),
        //):DataColumn(label: Container()),
        DataColumn(
          label: Text('状态'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('生产单号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('批次号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('库房位置'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('库位信息'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('物料编码'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('物料名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('规格型号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('单位'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('账面库存'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('实际库存'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('备注'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        StockMaterialcheckitem stockMaterialcheckitem =
            StockMaterialcheckitem.fromMap(m);
        return [
          //isDisplayDesktop(context)?DataCell(
          //  CryButtonBar(
          //    children: [
          //      CryButton(
          //          iconData: Icons.edit,
          //          tip: S.of(context).modify,
          //          onPressed: () => _edit(stockMaterialcheckitem)),
          //    ],
          //  ),
          // ):DataCell(Container()),
          stockMaterialcheckitem.isCheck=='1'?
          DataCell(Text('已盘点',style: TextStyle(color: Colors.redAccent),)):
          DataCell(Text('未盘点',style: TextStyle(color: Colors.green),)),
          DataCell(Text(stockMaterialcheckitem.productorderno ?? '--')),
          DataCell(Text(stockMaterialcheckitem.batchno ?? '--')),
          DataCell(Text(stockMaterialcheckitem.locationName ?? '--')),
          DataCell(Text(stockMaterialcheckitem.shelvesName ?? '--')),
          DataCell(Text(stockMaterialcheckitem.productCode ?? '--')),
          DataCell(Text(stockMaterialcheckitem.productName ?? '--')),
          DataCell(Text(stockMaterialcheckitem.productDesc ?? '--')),
          DataCell(Text(stockMaterialcheckitem.unit ?? '--')),
          DataCell(Text(stockMaterialcheckitem.planQty ?? '--')),
          DataCell(Text(stockMaterialcheckitem.stockqty ?? '--')),
          DataCell(Text(stockMaterialcheckitem.remark ?? '--')),
        ];
      },
    );
    _getSelectList();
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            DynamicDataApi.getModels(model: 'stock.materialcheckitem',key: 'check_id',val: int.parse(stockMaterialcheckitem.checkId!)).then((ResponseBodyApi res){
              if (!res.success!) {
                //CryUtils.message(re s.message!);
                return;
              }
              bool flag = false;
              for(var i = 0;i < res.data.length; i++){
                if(res.data[i]['is_check'] != '1'){
                  flag = true;
                  break;
                }
              }
              if(flag){
                CryUtils.message("请盘点所有的产品");
                return ;
              }
              StockMaterialcheckOdooApi.saveOrUpdate({
                'id':stockMaterialcheckitem.checkId,
                'inventory_id':userInfo.userId,
                'inventory_time': DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()),
                'is_check': '1'
              }).then((ResponseBodyApi res) {
                print(res);
                if (!res.success!) {
                  //CryUtils.message(re s.message!);
                  return;
                }
                Navigator.pop(context, true);
                CryUtils.message(S.of(context).saved);
              });
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text('盘点'),
      ),
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
      bottomNavigationBar: buttonBar,
    );
    return result;
  }

  _edit(StockMaterialcheckitem stockMaterialcheckitem) async {
    stockMaterialcheckitem.stockqty = stockMaterialcheckitem.planQty;
    stockMaterialcheckitem.checkId = widget.stockMaterialcheckitem.checkId;
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: StockMaterialcheckitemEdit(
          stockMaterialcheckitem: stockMaterialcheckitem,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _query() {
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    stockMaterialcheckitem.checkId = widget.stockMaterialcheckitem.checkId;
    ResponseBodyApi responseBodyApi = await StockMaterialcheckitemOdooApi.page(
        data: {
          "page": page,
          "domainList": stockMaterialcheckitem.toDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockMaterialcheckitem>(
                (e) => StockMaterialcheckitem.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.edit) {
          _edit(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('手动盘点'),
          ),
        ),
      ],
    );
  }
}
